package com.example.demo;

import javax.annotation.PostConstruct;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.jms.client.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ConsumerListener implements MessageListener {
	@Autowired
	private ActiveMQConnectionFactory factory;
	@Autowired
	public ConsumerListener(ActiveMQConnectionFactory factory) {
		this.factory = factory;
	}

	@Override
	public void onMessage(Message message) {
		if (message instanceof TextMessage) {
			TextMessage tm = (TextMessage) message;
			try {
				System.out.println("==收到消息啦：" + tm.getText());
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}

	@PostConstruct
	public void init() {
		int size = factory.getThreadPoolMaxSize();
		for (int i = 0; i < size; i++) {
			Connection cnn = null;
			Session session = null;
			try {
				cnn = factory.createQueueConnection();
				session = cnn.createSession();
				MessageConsumer consumer = session.createConsumer(new ActiveMQQueue("test.queue"));
				cnn.start();
				consumer.setMessageListener(this);
			} catch (JMSException e) {
				e.printStackTrace();
			}

		}
	}
}
